package com.zx._03_并发.chapter_00_lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class MyLock {


    /**
     * 锁的基础
     */
    abstract static class Sync extends AbstractQueuedSynchronizer {

        private static final long serialVersionUID = -5179523762034025860L;

        /**
         * 实现非公平锁的尝试申请。
         * tryAcquire方法 需要子类实现
         */
        final boolean nonfairTryAcquire(int acquires) {
            // 获得当前线程
            final Thread current = Thread.currentThread();
            // 获得锁的状态
            int c = getState();
            // 1. 未加锁
            if (c == 0) {
                // 尝试CAS修改一次状态，由0到1
                if (compareAndSetState(0, acquires)) {
                    // 修改成功了，设置当前线程  独占锁
                    setExclusiveOwnerThread(current);
                    // 加锁成功
                    return true;
                }
            }
            // 2. 判断独占锁是否是当前线程(实现重入锁)
            else if (current == getExclusiveOwnerThread()) {
                // 计算重入加锁的次数
                int nextc = c + acquires;
                // 超过最大锁计数。比如超过 Integer.MAX_VALUE
                if (nextc < 0) {
                    throw new Error("Maximum lock count exceeded");
                }
                // 设置重入的次数
                setState(nextc);
                return true;
            }
            return false;
        }

        /**
         * 释放锁
         *
         * @param releases
         * @return
         */
        @Override
        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread()) {
                throw new IllegalMonitorStateException();
            }
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

        /**
         * 是否已经被当前线程独占
         *
         * @return
         */
        @Override
        protected final boolean isHeldExclusively() {
            // While we must in general read state before owner,
            // we don't need to do so to check if current thread is owner
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

        // Methods relayed from outer class

        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        final boolean isLocked() {
            return getState() != 0;
        }

        /**
         * Reconstitutes the instance from a stream (that is, deserializes it).
         */
        private void readObject(java.io.ObjectInputStream s)
                throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

    /**
     * 非公平锁
     */
    static final class NonfairSync extends Sync {

        private static final long serialVersionUID = 7316153563782823691L;

        @Override
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    /**
     * 公平锁
     */
    static final class FairSync extends Sync {

        private static final long serialVersionUID = -3000897897090466540L;

        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        @Override
        protected final boolean tryAcquire(int acquires) {
            // 获得当前线程
            final Thread current = Thread.currentThread();
            // 获得锁的状态
            int c = getState();
            // 1. 未加锁
            if (c == 0) {
                // 1.1 判断是否前端已经有排队的线程
                if (!hasQueuedPredecessors() &&
                        // 1.2 没有排队的话，尝试CAS修改一次状态，由0到1
                        compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            // 2. 判断独占锁是否是当前线程(实现重入锁)
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) {
                    throw new Error("Maximum lock count exceeded");
                }
                setState(nextc);
                return true;
            }
            return false;
        }
    }
}
